package com.sdu.cloudservice.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.sdu.cloudservice.dto.Envelope;
import com.sdu.cloudservice.entity.AdminEntity;
import com.sdu.cloudservice.entity.UserEntity;
import org.springframework.util.DigestUtils;

/**
 * 获取字符串的md5摘要
 *
 * @author zekdot
 */
public class PasswordUtil {
    private static String salt="shudaixiong";   //盐
    public static String getMd5(String value) {
        value=new StringBuffer().append(salt).append(value).toString(); //加盐做md5
        return DigestUtils.md5DigestAsHex(value.getBytes());
    }

    /**
     * 获取用户的token
     * @param userEntity
     * @return
     */
    public static String getToken(UserEntity userEntity){
        String token="";
        // 生成token并进行存储
        token= JWT.create()
                .withAudience(userEntity.getUsername())
                .withClaim("identity","user")
                .sign(Algorithm.HMAC256(userEntity.getPassword()));
        return token;
    }

    /**
     * 获取管理员的token
     * @param adminEntity
     * @return
     */
    public static String getToken(AdminEntity adminEntity){
        String token="";
        // 生成token并进行存储
        token= JWT.create()
                .withAudience(adminEntity.getUsername())
                .withClaim("identity","admin")
                .sign(Algorithm.HMAC256(adminEntity.getPassword()));
        return token;
    }

    /**
     * 根据token获得角色
     * @param token
     * @return
     */
    public static String getRole(String token){
        if(token == null)
            return null;
        // 从token还原角色
        String role = JWT.decode(token).getClaim("identity").asString();
        // 还原用户名
        return role;
    }

    /**
     * 根据token 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token){
        if(token == null)
            return null;
        // 从token还原角色
        String username = JWT.decode(token).getAudience().get(0);
        // 还原用户名
        return username;
    }
    public static void main(String args[]){
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("zekdot");
        userEntity.setPassword("123456");
        String token = getToken(userEntity);
        System.out.println(JWT.decode(token).getAudience().get(0));
        System.out.println(JWT.decode(token).getClaim("identity").asString());
    }
}
